import { useEffect, useMemo, useState } from 'react'
import { List, Divider, Selector, Button, Empty, SpinLoading, NavBar } from 'antd-mobile'
import { SearchOutline } from 'antd-mobile-icons'
import { request } from '../axios/request'
import { useNavigate } from 'react-router-dom'
import styles from './index.module.css'

type DrugItem = {
  id: string
  name: string
  image?: string
  price?: number
  state?: string
  desc?: string
}

type ApiDrugRaw = {
  restorativesid?: string | number
  restorativeid?: string | number
  id?: string | number
  restorativesname?: string
  restorativevname?: string
  restorativesvname?: string
  name?: string
  restorativesprice?: number | string
  price?: number | string
  state?: string
  spec?: string
  desc?: string
}

const categoryOptions = [
  { label: '全部', value: '' },
  { label: '男科用药', value: '男科用药' },
  { label: '皮肤用药', value: '皮肤用药' },
]

function Index() {
  const navigate = useNavigate()
  const [search, setSearch] = useState('')
  const [state, setState] = useState<string>('')
  const [pageCode, setPageCode] = useState<number>(1)
  const [pageSize] = useState<number>(10)
  const [loading, setLoading] = useState<boolean>(false)
  const [list, setList] = useState<DrugItem[]>([])
  const [total, setTotal] = useState<number>(0)

  const params = useMemo(() => ({ pageCode, pageSize, state, search }), [pageCode, pageSize, state, search])

  const fetchList = async () => {
    try {
      setLoading(true)
      const res = await request.get('/restorative/list', { params })
      // 兼容两种返回格式：数组 或 {records,total}
      const rawData = res?.data?.data
      let items: ApiDrugRaw[] = []
      let totalCount = 0

      if (Array.isArray(rawData)) {
        items = rawData as ApiDrugRaw[]
        totalCount = rawData.length
      } else if (rawData && Array.isArray(rawData.records)) {
        items = rawData.records as ApiDrugRaw[]
        totalCount = Number(rawData.total || rawData.records.length || 0)
      }

      const mapped: DrugItem[] = items.map((it) => ({
        id: String(it.restorativesid ?? it.restorativeid ?? it.id ?? ''),
        name: String(it.restorativesname ?? it.restorativevname ?? it.restorativesvname ?? it.name ?? ''),
        price: Number(it.restorativesprice ?? it.price ?? 0) || undefined,
        state: it.state,
        desc: it.spec ?? it.desc ?? ''
      }))

      setList(mapped)
      setTotal(totalCount)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchList()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageCode, state])

  const onSearch = (val: string) => {
    setSearch(val)
  }

  const onSearchSubmit = () => {
    setPageCode(1)
    fetchList()
  }

  const onCategoryChange = (values: string[]) => {
    const value = values?.[0] ?? ''
    setState(value)
    setPageCode(1)
  }

  const hasMore = useMemo(() => list.length < total, [list.length, total])

  const loadMore = () => {
    if (!hasMore || loading) return
    const next = pageCode + 1
    setPageCode(next)
  }

  const handleBack = () => {
    navigate(-1)
  }

  return (
    <div className={styles.page}>
      {/* 顶部导航栏 */}
      <NavBar onBack={handleBack} style={{ backgroundColor: '#fff' }}>
        药品搜索
      </NavBar>
      <div className={styles.searchWrapper}>
        <div className={styles.searchInputBox}>
          <SearchOutline className={styles.searchIcon} />
          <input
            className={styles.input}
            value={search}
            onChange={(e)=>onSearch(e.target.value)}
            placeholder="搜索药品名称"
          />
          <div className={styles.vDivider}></div>
          <button className={styles.searchBtn} onClick={onSearchSubmit}>搜索</button>
        </div>
      </div>

      <div className={styles.content}>
        <Selector
          options={categoryOptions}
          value={[state]}
          onChange={onCategoryChange}
          showCheckMark={false}
        />
      </div>

      <Divider>搜索结果</Divider>

      {list.length === 0 && !loading ? (
        <Empty description="暂无数据" />
      ) : (
        <List>
          {list.map((item) => (
            <List.Item key={item.id} description={item.desc || item.state || ''} extra={item.price ? `￥${item.price}` : undefined}>
              {item.name}
            </List.Item>
          ))}
        </List>
      )}

      <div className={styles.loadMoreBox}>
        {loading ? (
          <SpinLoading />
        ) : (
          hasMore ? (
            <Button onClick={loadMore} color="primary" fill="outline" size="small">加载更多</Button>
          ) : (
            <span className={styles.noMore}>没有更多了</span>
          )
        )}
      </div>
    </div>
  )
}

export default Index
